﻿#include "stdafx.h"
namespace LK
{
	std::ostream& operator<<(std::ostream&o, PObject const&x)
	{
		return o << x.ToString();
	}
	std::wostream& operator<<(std::wostream&o, PObject const&x)
	{
		return o << x.ToString();
	}
	std::ostream& operator<<(std::ostream&o, Object const&x)
	{
		return o << x.ToString();
	}
	std::wostream& operator<<(std::wostream&o, Object const&x)
	{
		return o << x.ToString();
	}
	void Object::SwapWith(Object& x)
	{
		if (GetType() != x.GetType())throw PInvalidArgumentException(L"无效参数：指定的交换对象与当前对象类型不一致");
	}
	void PObject::AddTypeInfo()
	{
#ifdef LK_REFLECTION_
		//引用反射命名空间
		using namespace Reflection;
		//获取类库的引用
		PTypeLibrary lib = GetGlobleLibrary();
		//获取类库中的全局命名空间
		PNamespaceNode globle = lib.GetGlobleNamespaceRef();
		//添加LK命名空间
		PNamespaceNode space = globle.FindOrAddNamespace(L"LK");
		//在LK命名空间中添加PObject类型
		PTypeNode n = space.FindOrAddTypeNode(L"PObject", PType::Make<PObject>());
		//在PObject类型节点中添加成员函数
		n.AddFunction(L"GetType", &PObject::GetType);
		n.AddFunction(L"DynamicCall", (PObject(PObject::*)(PString const&, Collection::PArray<PObject>const&)const)&PObject::DynamicCall);
		n.AddFunction(L"SwapReference", &PObject::SwapReference);
		n.AddFunction(L"Equals", &PObject::Equals);
		n.AddFunction(L"TypeEqual", &PObject::TypeEqual);
		n.AddFunction(L"ReferenceEqual", &PObject::ReferenceEqual);
		n.AddFunction(L"IsNull", &PObject::IsNull);
		n.AddFunction(L"ToString", &PObject::ToString);
#endif
	}
	bool PObject::TypeEqual(PObject t1, PObject t2) { if (!t1.GetPtr() || t2.GetPtr())return false; return ReferenceEqual(t1.GetType(), t2.GetType()); }
	PObject PObject::DynamicCall(PString const&functionName, Collection::PArray<PObject>const &args)const
	{
#ifdef LK_REFLECTION_
		Reflection::PTypeNode tn = Reflection::GetGlobleLibrary().GetTypeNodeByInfo(GetType());
		if (tn.IsNull())throw PException(L"类库中找不到指定的类型");
		Reflection::PFunctionNode node = tn.FindNodeByNameInClass(functionName).CastTo<Reflection::PFunctionNode>();
		if (node.IsNull())throw PException(L"类型节点中找不到指定名称的函数");
		return node.DynamicCall(*this, args);
#else
		throw PNotSupportException(L"DynamicCall需要Reflection支持");
#endif
	}
}